package com.leantech.android.browser.dialog

import android.content.Context
import android.view.ViewGroup
import com.leantech.android.browser.R
import com.leantech.android.browser.databinding.DialogSingleEditBinding
import com.leantech.android.browser.utils.onThrottleClick
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.util.QMUIKeyboardHelper
import com.qmuiteam.qmui.widget.dialog.QMUIBaseDialog

class SingleEditDialog(
    context: Context,
    private val onSure: (dialog: SingleEditDialog, originText: String?, newText: String?) -> Unit
) : QMUIBaseDialog(context, R.style.MessageDialogStyle) {


    private var title: String? = null
    private var content: String? = null

    private val binding =
        DialogSingleEditBinding.inflate(layoutInflater)

    init {
        setSkinManager(QMUISkinManager.defaultInstance(context))
        setContentView(
            binding.root, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
        )

        binding.btnRefresh.onThrottleClick {
            binding.content.text?.clear()
        }

        binding.btnSure.onThrottleClick {
            val text = binding.content.text?.toString()
            if (!text.isNullOrBlank()) {
                onSure(this, content, text)
            }
        }

        binding.btnCancel.onThrottleClick {
            dismiss()
        }
    }

    fun setTitle(title: String) = apply {
        this.title = title
    }

    fun setContent(content: String) = apply {
        this.content = content
    }

    override fun show() {
        binding.title.text = title
        binding.content.setText(content)
        val txt = content
        if (!txt.isNullOrEmpty()) {
            val lastIndexOfDot = txt.lastIndexOf(".")
            binding.content.setSelection(0, lastIndexOfDot)
        }

        super.show()
        binding.content.requestFocus()
        QMUIKeyboardHelper.showKeyboard(binding.content, true)
    }

}